package com.example.websoketclient.client.impl;

import com.example.websoketclient.client.Client;
import okhttp3.*;
import okio.ByteString;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhenWuWang
 */
public class OkHttpWebSocketClient implements Client
{
    private final static OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
            .readTimeout(30, TimeUnit.SECONDS)//设置读取超时时间
            .writeTimeout(30, TimeUnit.SECONDS)//设置写的超时时间
            .connectTimeout(30, TimeUnit.SECONDS)//设置连接超时时间
            .cookieJar(new CookieJar()
            {
                private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies)
                {
                    cookieStore.put(url.host(), cookies);
                    for (Cookie cookie : cookies)
                    {
                        System.out.println(cookie);
                    }
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url)
                {
                    List<Cookie> cookies = cookieStore.get(url.host());
                    return cookies != null ? cookies : new ArrayList<>();
                }
            })
            .build();

    @Override
    public void start()
    {
        login();
        Request request = new Request
                .Builder()
                .url("ws://localhost:8080/websocket/socketServer.do")
                .build();
        EchoWebSocketListener socketListener = new EchoWebSocketListener();
        WebSocket webSocket = OK_HTTP_CLIENT.newWebSocket(request, socketListener);
        OK_HTTP_CLIENT.dispatcher().executorService().shutdown();
        webSocket.send("哈喽,连接一下啊");
    }

    private static void login()
    {
        Request request = new Request
                .Builder()
                .url("http://localhost:8080/websocket/login?userName=ruby")
                .build();
        try
        {
            Response response = OK_HTTP_CLIENT.newCall(request).execute();
            System.out.println(new String(response.body().bytes()));
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private static class EchoWebSocketListener extends WebSocketListener
    {
        @Override
        public void onClosed(WebSocket webSocket, int code, String reason)
        {
            System.out.println("链接已关闭");
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason)
        {
            System.out.println("链接正在关闭...");
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response)
        {
            System.out.println("链接失败：" + t.getMessage());
        }

        @Override
        public void onMessage(WebSocket webSocket, String msg)
        {
            System.out.println("收到消息==========" + msg);
            if (msg.equals("over"))
            {
                webSocket.close(1000, null);
            }
        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes)
        {
            String msg = bytes.toString();
            onMessage(webSocket, msg);
        }

        @Override
        public void onOpen(WebSocket webSocket, Response response)
        {
            System.out.println("握手成功");
        }
    }
}
